package com.flx.websocket;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WebSocketService
 * @Description TODO
 * @Author 23207
 * @Date 2025/4/29 13:27
 * @Version 1.0
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketService {
  private static Map<String, Session> sessionMap = new HashMap<>();

  /**
   * 连接成功
   * @param session
   * @param sid
   */
  @OnOpen
  public void onOpen(Session session,@PathParam("sid") String sid) {
    System.out.println("用户: " + sid + "连接成功");
    sessionMap.put(sid, session);
  }

  /**
   * 接收消息
   * @param message
   * @param sid
   */
  @OnMessage
  public void onMessage(String message, @PathParam("sid") String sid) {
    System.out.println("用户: " + sid + "发送消息: " + message);
  }

  /**
   * 断开连接
   * @param sid
   */
  @OnClose
  public void onClose(@PathParam("sid")String sid) {
    sessionMap.remove(sid);
    System.out.println("用户: " + sid + "断开连接");
  }

  /**
   * 发送消息给所有用户
   * @param message
   */
  public void sendToAllUser(String message) {
    Collection<Session> sessions = sessionMap.values();
    for (Session session : sessions) {
      try {
        session.getAsyncRemote().sendText(message);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}
